package com.squareshoot.picCheckin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AddVenue extends Activity {
	
	Button addVenueButton;
	EditText venueName,venueAddress,venueCrossstreet,venueZip,venueCity,venueState,venuePhone;
	ProgressBar progressLoading;
	String username, password;
	double latitude,longitude;
	boolean sendtotwitter,sendtofacebook;
	Uri photo;
	boolean photoSelected=false;
	private Address adresse;
	private AddVenueTask venueTask;
	
	private TextWatcher textWatcher = new TextWatcher() {
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
		}
		
		public void beforeTextChanged(CharSequence s, int start, int count,int after) {
			// TODO Auto-generated method stub
		}
		
		public void afterTextChanged(Editable s) {
			if(s.length()>0)
				addVenueButton.setEnabled(true);
			else
				addVenueButton.setEnabled(false);
		}
	};
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addvenue);
		
		if(Common.HIGHDEBUG)
			Log.d(Common.TAG,"onCreate : AddVenue");
		
		progressLoading = (ProgressBar)findViewById(R.id.indeterminateProgressBar);
		progressLoading.setVisibility(View.GONE);
		
		Bundle bundle = this.getIntent().getExtras();
		username = bundle.getString("username");
		password = bundle.getString("password");
		latitude = bundle.getDouble("latitude");
		longitude = bundle.getDouble("longitude");
		sendtotwitter = bundle.getBoolean("sendtotwitter");
		sendtofacebook = bundle.getBoolean("sendtofacebook");
		if(bundle.containsKey("photo")){
			photo = (Uri)bundle.get("photo");
			photoSelected = true;
		}
		
		addVenueButton = (Button)findViewById(R.id.addVenueButton);
		venueName = (EditText)findViewById(R.id.addVenueName);
		venueName.addTextChangedListener(textWatcher);
		
		venueAddress = (EditText)findViewById(R.id.addVenueAddress);
		venueCrossstreet = (EditText)findViewById(R.id.addVenueCrossStreet);
		venueZip = (EditText)findViewById(R.id.addVenueZip);
		venueCity = (EditText)findViewById(R.id.addVenueCity);
		venueState = (EditText)findViewById(R.id.addVenueState);
		venuePhone = (EditText)findViewById(R.id.addVenuePhone);
		
		if(savedInstanceState==null){
			if(bundle.containsKey("adresse")){
				adresse=bundle.getParcelable("adresse");
				if(Common.HIGHDEBUG)
					Log.d(Common.TAG,"adresse: "+adresse);
				venueAddress.setText(adresse.getAddressLine(0));
				venueZip.setText(adresse.getPostalCode());
				venueCity.setText(adresse.getLocality());
				if(adresse.getCountryCode().compareTo("US")==0){
					venueState.setText(adresse.getAdminArea());
				}else{
					venueState.setText(adresse.getCountryName());
				}
				
			}
		}else{
			if(getLastNonConfigurationInstance()!=null){
				venueTask=(AddVenueTask)getLastNonConfigurationInstance();
				venueTask.setActivity(this);
			}
		}

		addVenueButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				venueTask = new AddVenueTask();
				venueTask.setActivity(AddVenue.this);
				venueTask.execute();
			}
		});
	}
	
	public Object onRetainNonConfigurationInstance() {
		if(venueTask!=null){
			venueTask.setActivity(null);
			return venueTask;
		}
		return null;
	}
	
	private void onAddVenueCompleted(Bundle data){
		if(!data.containsKey("eMessage")){
			String venue = data.getString("addvenue");
			if(Common.DEBUG)
				Log.d(Common.TAG,"addvenue: "+venue);
			String venueId = null;
			JSONObject jVenue = null;
			try {
				jVenue = new JSONObject(venue);
				jVenue = jVenue.getJSONObject("venue");
				venueId = jVenue.getString("id");
				startVenueDetails(venueId);
				
			}catch(JSONException e){
				String error=null;
				if(jVenue!=null && jVenue.has("error"))
					try {
						error = jVenue.getString("error");
					} catch (JSONException e1) {
						error = getString(R.string.unknownerror);
					}
				Toast erreurToast = Toast.makeText(AddVenue.this,error,Toast.LENGTH_SHORT);
				erreurToast.setGravity(Gravity.CENTER, 0, 0);
				erreurToast.show();
			}
		}else{
			//Erreur de type IOException dans la thread AddVenue
			//En gros, pb de communication avec le serveur
			if(Common.DEBUG)
				Log.d(Common.TAG,"addvenue error: "+data.getString("eMessage"));
			Toast erreurToast = Toast.makeText(AddVenue.this,data.getString("eMessage"),Toast.LENGTH_SHORT);
			erreurToast.setGravity(Gravity.CENTER, 0, 0);
			erreurToast.show();
		}
	}
	
	private class AddVenueTask extends AsyncTask<String,String,Message>{
		private Message msg;
		private AddVenue activity;
		private boolean completed=false;

		protected void onPreExecute() {
			progressLoading.setVisibility(View.VISIBLE);
			addVenueButton.setEnabled(false);
			msg=Message.obtain();
		}

		protected Message doInBackground(String... parameters) {
			Bundle data = new Bundle();
			
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("name",venueName.getText().toString()));
			if(venueAddress.getText().length()>0)
				params.add(new BasicNameValuePair("address",venueAddress.getText().toString()));
			if(venueCrossstreet.getText().length()>0)
				params.add(new BasicNameValuePair("crossstreet",venueCrossstreet.getText().toString()));
			if(venueCity.getText().length()>0)
				params.add(new BasicNameValuePair("city",venueCity.getText().toString()));
			if(venueState.getText().length()>0)
				params.add(new BasicNameValuePair("state",venueState.getText().toString()));
			if(venueZip.getText().length()>0)
				params.add(new BasicNameValuePair("zip",venueZip.getText().toString()));
			if(venuePhone.getText().length()>0)
				params.add(new BasicNameValuePair("phone",venuePhone.getText().toString()));
			if(latitude!=0.0)
				params.add(new BasicNameValuePair("geolat",""+latitude));
			if(longitude!=0.0)
				params.add(new BasicNameValuePair("geolong",""+longitude));
			
			String urlAddVenue = "http://api.foursquare.com/v1/addvenue.json";
			String addVenueResponse = null;
			try {
				addVenueResponse = Common.postUrlDataAuth(urlAddVenue,username,password,params);
				data.putString("addvenue",addVenueResponse);
			} catch (IOException e) {
				data.putString("eMessage",e.getMessage());
			}
			msg.setData(data);
			return msg;
		}

		protected void onPostExecute(Message msg) {
			completed=true;
			if(activity!=null)
				endTask();
		}
		
		protected void endTask() {
			activity.venueTask=null;
			progressLoading.setVisibility(View.GONE);
			addVenueButton.setEnabled(true);
			onAddVenueCompleted(msg.getData());
		}
		
		private void setActivity(AddVenue activity) {
			this.activity = activity;
			if ( completed ) {
				endTask();
			}
		}
	}
	
	private void startVenueDetails(String venueId){
		Intent i=new Intent(AddVenue.this,VenueDetails.class);
		Bundle bundle = new Bundle();
		bundle.putString("venueId",venueId);
		bundle.putString("username",username);
		bundle.putString("password",password);
		bundle.putDouble("latitude",latitude);
		bundle.putDouble("longitude",longitude);
		bundle.putBoolean("sendtotwitter",sendtotwitter);
		bundle.putBoolean("sendtofacebook",sendtofacebook);
		if(photoSelected)
			bundle.putParcelable("photo",photo);
		i.putExtras(bundle);
		startActivity(i);
	}

}
